(function (factory) {
    const urls = {
        checkFileMd5: "/edufs/file/uploadmd5",
        uploadFile  : "/edufs/file/uploadFile",
    };

    const __api__ = {};
    
    /** 
     * 批量上传图片
     */
    let _INDEX = 1;
    __api__.uploadImagePipe = function (files, options={}, callback, fail) {
        // options = {
        //     non_upload_yun: true
        // };
    
        /** 
         * 获取图片详细及服务器信息
         */
        function getFileInformation(files, callback, index=0) {
            if (files[index]) {
                files[index].blob = URL.createObjectURL(files[index]);
    
                util.getFileMd5(files[index], function (op) {
                    files[index].KB = op.KB;
                    files[index].MB = op.MB;
                    files[index].GB = op.GB;
                    files[index].md5 = op.md5;
    
                    getFileInformation(files, callback, index + 1);
                });
            } else {
                if (options.non_upload_yun) {
                    callback && callback(files);
                } else {
                    // 当处理完毕md5后，下一步获取文件id
                    getFileUrl(files, callback);
                }
            }
        }
    
        let icons = {
            // office
            ".xls": "excel",
            ".xlsx": "excel",
            ".doc": "word",
            ".docx": "word",
            ".ppt": "ppt",
            ".pptx": "ppt",
    
            // 媒体
            ".mp3": "music",
            ".wav": "music",
            ".mp4": "video",
            ".flv": "video",
            ".mov": "video",
            ".jpg": "pic",
            ".jpeg": "pic",
            ".png": "pic",
            ".gif": "pic",
            ".bmp": "pic",
            ".ico": "pic",
            ".raw": "pic",
    
            // pdf
            ".pdf": "pdf",
    
            // 文本
            ".txt": "txt",
            ".txt": "txt",
            ".html": "txt",
            ".htm": "txt",
            ".asp": "txt",
            ".jsp": "txt",
            ".xml": "txt",
            ".json": "txt",
            ".properties": "txt",
            ".md": "txt",
            ".gitignore": "txt",
            ".java": "txt",
            ".py": "txt",
            ".c": "txt",
            ".cpp": "txt",
            ".sql": "txt",
            ".sh": "txt",
            ".bat": "txt",
            ".m": "txt",
            ".bas": "txt",
            ".prg": "txt",
            ".cmd": "txt",
    
            // 压缩包
            ".rar": "zip",
            ".zip": "zip",
            ".jar": "zip",
            ".7-zip": "zip",
            ".tar": "zip",
            ".gzip": "zip",
            ".7z": "zip",
        };
    
        /** 
         * 获取图片远程信息
         */
        function getFileUrl(files, callback, index=0) {
            if (files[index]) {
                api.getOriginImage(files[index], function (info) {
                    files[index].ufid        = info.ufid;
                    files[index].ext         = info.ext;
                    files[index].index       = info.id + "_" + _INDEX++;
                    files[index].id          = info.id;
                    files[index].originUrl   = info.url;
                    files[index].previewUrl  = "/edufs/preview/" + info.id;
                    files[index].downloadUrl = "/edufs/fdownload/" + info.id;
    
                    if (icons.hasOwnProperty(info.ext)) {
                        files[index].iconType = icons[info.ext];
                        files[index].iconUrl = `/edufs/html/web/files_icon/${files[index].iconType}.png`;
                    } else {
                        files[index].iconType = "others";
                        files[index].iconUrl = `/edufs/html/web/files_icon/others.png`;
                    }
                    
                    cache.set("files_" + files[index].id, files[index]);
                    getFileUrl(files, callback, index + 1);
                }, function (e) {
                    fail && fail(e);
                });
            } else {
                callback && callback(files);
            }
        }
    
        /** 
         * 获取图片服务器ID
         */
        api.getOriginImage = function (file, callback, fail) {
            let ext = "";
            let doc_index = file.name.lastIndexOf(".");
            if (doc_index != -1) {
                ext = file.name.slice(doc_index).toLowerCase();
            }
            api.checkFileMd5(file, function (data) {
                if (data === false) {
                    api.uploadImageToServer(file, function (data) {
                        callback && callback({
                            ufid: data.id,
                            id  : data.id + ext,
                            ext : ext,
                            url : data.path + "y" + data.id + ext
                        });
                    }, function (e) {
                        fail && fail(e);
                    });
                } else {
                    callback && callback({
                        ufid: data.id,
                        id  : data.id + ext,
                        ext : ext,
                        url : data.path + "y" + data.id + ext
                    });
                }
            }, function (e) {
                fail && fail(e);
            });
        }
    
        /** 
         * 检测图片md5在服务器上存在情况
         */
        api.checkFileMd5 = function (file, callback, fail) {
            api.request(urls.checkFileMd5, {
                md5: file.md5
            }, {
                loading: false,
                done(result) {
                    callback && callback(result.data.id == "0" ? false : result.data);
                },
                fail(e) {
                    fail({
                        message: "上传失败"
                    })
                }
            });
        }
    
        /** 
         * 上传图片到服务器
         */
        api.uploadImageToServer = function (file, callback, fail) {
            api.request(urls.uploadFile, {
                md5: file.md5,
                file: file
            }, {
                loading: false,
                done(result) {
                    callback && callback(result.data);
                },
                fail(e) {
                    fail({
                        message: "上传失败"
                    })
                }
            });
        }
    
        return getFileInformation(files, callback);
    }
    
    /** 
     * 开始上传图片
     */
    __api__.uploadImage = function ({type, size=50}, options, callback, fail) {
        options = util.objectInset({
            multiple: false,
            limit: 1,
            limitError: "",
            type: "",
            accept: "",
            acceptError: "",
            // 是否不上传到云盘并获取远程文件信息
            non_upload_yun: false,
            // 指定file文件数组，不指定时为自动上传
            files: null
        }, options);

        if (!util.isEmpty(type)) {
            options.type = type;
        }

        options.limitError = options.limitError || "最多上传" + options.limit + "张图片";

        switch (options.type) {
            case "image":
                options.accept = ".png,.jpg,.jpeg";
                options.acceptAttr = "image/*";
                options.acceptError = "只能上传png、jpg、jpeg格式的图片";
                break;
            case "video":
                options.accept = ".mp4,.wav,.flv,.mov";
                options.acceptAttr = ".mp4,.wav,.flv,.mov";
                options.acceptError = "只能上传mp4,wav,flv,mov格式的图片";
                break;
            case "excel":
                options.accept = ".xls,.xlsx";
                options.acceptAttr = ".xls,.xlsx";
                options.acceptError = "只能上传xls、xlsx格式的文件";
                break;
            case "file":
                options.accept = "*";
                options.acceptError = "";
        }
    
        let upload = function (files) {
            // 如果未上传内容忽略本次操作
            if (files.length == 0) {
                return;
            }

            // 如果超过图片限制，只上传最大图片数
            if (options.limit && files.length > options.limit) {
                files = files.slice(0, options.limit);
            }

            // 过滤前图片数
            let filesCount = files.length;
            // 过滤原因
            let imageTips = [];

            // 遍历图片，检测图片格式和大小，并过滤掉不合格的图片
            files = files.filter(file => {
                if (file.name.indexOf(".") == -1) {
                    if (!imageTips[0]) {
                        imageTips[0] = options.acceptError;
                    }
                    return false;
                }
                let doc_index = file.name.lastIndexOf(".");
                if (options.accept !== "*" && !options.accept.split(",").includes(file.name.slice(doc_index).toLowerCase())) {
                    if (!imageTips[0]) {
                        imageTips[0] = options.acceptError;
                    }
                    return false;
                }
                if (file.size > 1024 * 1024 * size) {
                    if (!imageTips[1]) {
                        imageTips[1] = "文件大小不能超过"+ size +"M";
                    }
                    return false;
                }

                return true;
            });

            // 如果过滤掉了部分图片，弹出相对应的过滤原因但不终止本次操作
            if (filesCount != files.length) {
                weuialert(imageTips.filter(i => !util.isEmpty(i)).join("，"));
            }

            // 如果过滤之后还有图片待上传，上传图片
            if (files.length > 0) {
                // 上传没有loading提示，在这里添加总提示
                let loading = weui.loading("上传中");
                __api__.uploadImagePipe(files, {
                    non_upload_yun: options.non_upload_yun
                }, function (files) {
                    loading.hide();
                    callback && callback(files);
                }, function (e) {
                    loading.hide();
                    fail && fail(e);
                });
            }
        }
        
        if (util.isEmpty(options.files)) {
            var InputFileDM;
        
            if (options.multiple) {
                InputFileDM = component.create("<input type='file' accept='"+ options.acceptAttr +"' multiple style='display:none'/>");
            } else {
                InputFileDM = component.create("<input type='file' accept='"+ options.acceptAttr +"' style='display:none'/>");
            }
            InputFileDM.addEventListener("change", function (e) {
                // 文件组转为数组
                var files = util.like2Array(e.target.files);
                upload(files);
            });

            document.body.appendChild(InputFileDM.el);
            InputFileDM.el.click();
        } else {
            upload(options.files);
        }
    }
    
    factory(__api__);
})(function (__api__) {
    /** 
     * 开始上传图片
     * @param {Bool} multiple 是否开启多文件上传，默认false不开启
     * @param {Number} limit 最多选择文件个数，默认为1个
     * @param {String} limitError 多文件上传时使用，选择文件数超出limit值时给出提示文字，默认无文字
     */
    api.uploadImage = __api__.uploadImage.bind(api, {
        type: "image"
    });
    
    api.uploadVideo = __api__.uploadImage.bind(api, {
        type: "video",
        size: 30
    });
    
    api.uploadExcel = __api__.uploadImage.bind(api, {
        type: "excel"
    });

    api.uploadFile = __api__.uploadImage.bind(api, {
        type: "file"
    });
});
